<template>
	<view class="publish-page">
		<van-nav-bar title="发表文章" left-text="返回" left-arrow @click-left="Back" />

		<van-form @submit="onSubmit">
			<van-cell-group inset>
				<!-- 标题 -->
				<van-field v-model="bolgTitle" label="标题" name="bolgTitle" placeholder="请输入标题" />
				<!-- 正文 -->
				<van-field v-model="bolgArticle" rows="5" name="bolgArticle" label="正文" type="textarea" maxlength="300"
					placeholder="请输入正文" show-word-limit />

				<!-- 分类选择 -->
				<van-field v-model="result" is-link readonly name="bolgSortId" label="选择器" placeholder="点击选择标题"
					@click="showPicker = true" />
				<van-popup v-model:show="showPicker" position="bottom">
					<van-picker :columns="columns" @confirm="onConfirm" @cancel="showPicker = false" />
				</van-popup>

				<!-- 照片上传 -->
				<view class="upload">
					<img :src="photo" @click="updateImage" id="upload">
					<text class="upload-text ">
						上传图片
					</text>
				</view>

			</van-cell-group>
			<view style="margin: 16px;">
				<van-button round block type="primary" native-type="submit"> 提交 </van-button>
			</view>
		</van-form>



	</view>
</template>

<script setup>
	import {
		showSuccessToast,
	} from 'vant';
	import {
		ref
	} from 'vue'

	import $api from '../../request/index.js'


	let bolgTitle = ref('') // 博客标题
	let bolgArticle = ref('') // 博客正文



	const result = ref(''); // 选择器选择 结果
	const showPicker = ref(false); // 选择器的显示隐藏
	const columns = [{
			text: '西安-陕拾叁',
			value: 1
		},
		{
			text: '疯狂的牌照',
			value: 2
		},
		{
			text: '最美女骑士',
			value: 3
		},
		{
			text: '二手装备',
			value: 4
		},
		{
			text: '头盔控',
			value: 5
		},
		{
			text: '摩友帮选车',
			value: 6
		},
		{
			text: '摩旅日记',
			value: 7
		},
		{
			text: '好装备推荐',
			value: 8
		},
	]


	// 选择器确定
	const onConfirm = ({
		selectedOptions
	}) => {
		console.log(selectedOptions[0])
		result.value = selectedOptions[0]?.value;
		showPicker.value = false;
	};

	// 照片
	let photo = ref('../../static/icon/file_upload.png');

	// 头像上传
	const updateImage = () => {
		uni.chooseImage({
			count: 1, // 上传数量
			success: res => {
				let file = res.tempFilePaths[0]
				uni.uploadFile({
					url: '/api/admin/common/upload',
					name: 'file',
					filePath: file,
					success: res => {
						res = JSON.parse(res.data)
						photo.value = res.data
					}
				})
			}
		})
	}

	// 发表
	const onSubmit = values => {
		let data = values
		data.imgs = photo.value
		console.log(data)
		$api.post('/moto/bolg/publish', data).then(res => {
			if (res.code) {
				showSuccessToast(res.data)
				setTimeout(() => {
					uni.navigateBack()
				}, 1500)
			}
		})
	}


	// 返回按钮
	const Back = () => uni.navigateBack()
</script>

<style>
	.upload {
		padding: 20rpx;
		border-bottom: 1px solid #eee;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.upload>img {
		width: 100px;
		height: 100px;
		border: 1px solid #ddd;
		margin-top: 20rpx;
	}
</style>